package com.tfkj.contrller;

import com.tfkj.vo.InputStreamDTO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.RescaleOp;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import java.io.ByteArrayOutputStream;
import java.io.IOException;


public class PdfUtil {
    public static InputStreamDTO cropPDFPage(BufferedImage originalImage, Integer y1, Integer y2, Double height) throws IOException {
        int owidth = originalImage.getWidth();
        int oheight = originalImage.getHeight();
        Double rateH = oheight / height;
        // 裁剪图像
        BufferedImage croppedImage = originalImage.getSubimage(0, (int) (y1 * rateH), owidth, (int) ((y2 - y1) * rateH));

        // 将裁剪后的图像写入ByteArrayOutputStream
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(croppedImage, "png", baos); // 可以根据需要更改图像格式

        // 将ByteArrayOutputStream转换为ByteArrayInputStream
        InputStream croppedImageStream = new ByteArrayInputStream(baos.toByteArray());

        // 关闭ByteArrayOutputStream（在这个场景下不是必须的，因为已经转换成InputStream）
        baos.close();

        return new InputStreamDTO(croppedImageStream, baos.size());

    }

    public static BufferedImage getImageFromURL(String imageUrlString) throws Exception {
        URL imageUrl = new URL(imageUrlString);
        try (InputStream inputStream = imageUrl.openStream()) {
            // 直接从InputStream读取为BufferedImage
            BufferedImage image = ImageIO.read(inputStream);
            if (image == null) {
                throw new Exception("Failed to read image from the URL.");
            }
            return image;
        }
    }


    public static List<InputStreamDTO> cutPDFPage(MultipartFile file) throws IOException {
        try (PDDocument document = PDDocument.load(file.getBytes())) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            List<InputStreamDTO> imageBytesArray = new ArrayList<>();

            for (int page = 0; page < document.getNumberOfPages(); ++page) {
                // 渲染图像
                BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
                // 增强图像
                BufferedImage enhancedImage = enhanceImage(bim);
                // 使用 ByteArrayOutputStream 来捕获图片数据
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(enhancedImage, "png", baos);
                // 将 ByteArrayOutputStream 转换为 ByteArrayInputStream
                InputStream croppedImageStream = new ByteArrayInputStream(baos.toByteArray());
                InputStreamDTO dto = new InputStreamDTO(croppedImageStream, baos.size());
                imageBytesArray.add(dto);
            }
            return imageBytesArray;
        }
    }

    private static BufferedImage enhanceImage(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = result.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();

        // 增强对比度和亮度
        RescaleOp rescaleOp = new RescaleOp(1.3f, 10, null);
        result = rescaleOp.filter(result, null);

        // 遍历每个像素
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                Color color = new Color(result.getRGB(x, y));
                int red = color.getRed();
                int green = color.getGreen();
                int blue = color.getBlue();
                // 将接近白色的颜色转换为白色
                if (red > 210 && green > 210 && blue > 210) {
                    red = 255;
                    green = 255;
                    blue = 255;
                }
                if (red > 200 && red - green > 10 && red - blue > 10) {
                    red = 255;
                    green = 0;
                    blue = 0;
                }
                result.setRGB(x, y, new Color(red, green, blue).getRGB());
            }
        }
        // 将颜色空间转换为 sRGB 并增强红色
        ColorConvertOp colorConvertOp = new ColorConvertOp(image.getColorModel().getColorSpace(),
                java.awt.color.ColorSpace.getInstance(java.awt.color.ColorSpace.CS_sRGB), null);
        result = colorConvertOp.filter(result, null);
        return result;
    }



}